package com.lagou.handler;

import com.alibaba.fastjson.JSON;
import com.lagou.model.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    private ApplicationContext applicationContext;

    public UserServiceHandler(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        RpcRequest rpcRequest = JSON.parseObject(msg.toString()
                                                    .getBytes(Charset.defaultCharset()), RpcRequest.class);
        Class<?> serviceClass = Thread.currentThread()
                                      .getContextClassLoader()
                                      .loadClass(rpcRequest.getClassName());
        Object contextBean = applicationContext.getBean(serviceClass);
        Method method = serviceClass.getDeclaredMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        Object result = method.invoke(contextBean, rpcRequest.getParameters());
        ctx.writeAndFlush(result);


    }

}
